import { Injectable } from '@nestjs/common';
import { CreateDictDto } from './dto/create-dicts.dto';
import { UpdateDictDto } from './dto/update-dicts.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { SysDict } from './entities/dicts.entity';
import { In, Like, Repository } from 'typeorm';
import { SearchDto } from '@/common/dto/base-search.dto';
import { IdsDto } from '@/common/dto/ids.dto';

@Injectable()
export class DictService {
  constructor(
    @InjectRepository(SysDict)
    private readonly dictRepository: Repository<SysDict>,
  ) {}
  async findPage(query: SearchDto) {
    const page = query.pageNum || 1;
    const limit = query.pageSize || 10;

    const [data, count] = await this.dictRepository.findAndCount({
      where: [
        // 或查询
        { name: Like(`%${query.keywords || ''}%`) },
        { dictCode: Like(`%${query.keywords || ''}%`) },
      ],
      skip: (page - 1) * limit,
      take: limit,
    });

    return {
      list: data,
      total: count,
    };
  }
  create(createDictDto: CreateDictDto) {
    return this.dictRepository.save(createDictDto);
  }

  async findList() {
    const list = await this.dictRepository.find({});
    return list.map((item) => {
      return {
        label: item.name,
        value: item.dictCode,
        tag: '',
        children: [],
      };
    });
  }

  findOne(id: string) {
    return this.dictRepository.findOneBy({ id });
  }

  update(id: string, updateDictDto: UpdateDictDto) {
    return this.dictRepository.update(id, updateDictDto);
  }

  remove({ ids }: IdsDto) {
    return this.dictRepository.softDelete(ids.split(','));
  }
}
